package io.gitee.crud.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;
import java.util.Optional;

@Slf4j
@Component
public class HttpUtils {

    private static final String Authorization = "Authorization";

    @Autowired
    private RestTemplate restTemplate;

    public ResponseEntity<String> get(String url, String authorization, Map<String, Object> params) {
        HttpHeaders headers = new HttpHeaders();
        headers.set(Authorization, authorization);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if (!CollectionUtils.isEmpty(params)) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                builder.queryParam(entry.getKey(), entry.getValue());
            }
        }
        String urlStr = builder.toUriString();
        ResponseEntity<String> response;
        try {
            //log.info(JSONUtil.toJsonStr(headers));
            //log.info(urlStr);
            response = restTemplate.exchange(urlStr, HttpMethod.GET, new HttpEntity<>(headers), String.class);
        } catch (Exception e) {
            log.error("HTTP get error, url:{}", urlStr, e);
            throw new RuntimeException(e);
        }
        if (!HttpStatus.OK.equals(response.getStatusCode())) {
            throw new RuntimeException(String.format("HTTP get not ok, url: %s, statusCode: %d, response: %s",
                    urlStr, response.getStatusCodeValue(), Optional.ofNullable(response.getBody()).orElse("")));
        }
        return response;
    }

    public ResponseEntity<String> post(String url, String authorization, String requestBody) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set(Authorization, authorization);
        ResponseEntity<String> response;
        try {
            //log.info(url);
            //log.info(JSONUtil.toJsonStr(headers));
            //log.info(requestBody);
            response = restTemplate.postForEntity(url, new HttpEntity<>(requestBody, headers), String.class);
        } catch (Exception e) {
            log.error("HTTP post error, url:{}, requestBody:{}", url, requestBody, e);
            throw new RuntimeException(e);
        }
        if (!HttpStatus.OK.equals(response.getStatusCode())) {
            throw new RuntimeException(String.format("HTTP post not ok, url: %s, requestBody: %s, statusCode: %d, response: %s",
                    url, requestBody, response.getStatusCodeValue(), Optional.ofNullable(response.getBody()).orElse("")));
        }
        return response;
    }
}